import Vue from 'vue'
import Vuex from 'vuex'
// 案例的代码
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  // 所有的任务列表
  state: {
    // count: 0
    list: [],
    // 文本框的内容
    inputValue: 'aaa',
    nextId: 5,
    viewKey: 'all'
  },
  //  mutations 中是不能写异步操作代码 只有mutations 里的函数才能修改state 里的数据
  mutations: {
    initList (state, list) {
      state.list = list
    },
    inputValueEvent (state, val) {
      state.inputValue = val
    },
    addItem (state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    remoeItem (state, id) {
      const i = state.list.findIndex(x => x.id === id)
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    statusChange (state, param) {
      const i = state.list.findIndex(x => x.id === param.id)
      if (i !== -1) {
        state.list[i].done = param.status
      }
    },
    clean (state) {
      state.list = state.list.filter(x => x.done === false)
    },
    changeViewKey (state, key) {
      state.viewKey = key
    }
    // add (state) {
    //   state.count++
    // },
    // addN (state, step) {
    //   state.count += step
    // },
    // sub (state) {
    //   state.count--
    // },
    // subN (state, step) {
    //   state.count -= step
    // }
  },
  //  在actions中不能直接 修改state 中 的数据
  //  必须通过context.commit() 触发mutation 里的某个函数才行
  actions: {
    // actions 用于处理异步任务
    // addAsync (context) {
    //   setTimeout(() => {
    //     context.commit('add')
    //   }, 2000)
    // },
    // addNAsync (context, step) {
    //   setTimeout(() => {
    //     context.commit('addN', step)
    //   }, 2000)
    // },
    // subAsync (context) {
    //   setTimeout(() => {
    //     context.commit('sub')
    //   }, 2000)
    // },
    // subNAsync (context, step) {
    //   setTimeout(() => {
    //     context.commit('subN', step)
    //   }, 2000)
    // }
    // 案例的代码
    getList (context) {
      axios.get('/list.json').then(({ data }) => {
        console.log(data)
        context.commit('initList', data)
      })
    }
  },
  // getters 用于对Store 中的数据进行数据加工处理形成新的数据
  getters: {
    // showNum (state) {
    //   return `最新的数据的数量是${state.count}`
    // }
    undone (state) {
      return state.list.filter(x => x.done === false).length
    },
    infoList (state) {
      if (state.viewKey === 'all') {
        return state.list
      }
      if (state.viewKey === 'notdone') {
        return state.list.filter(x => x.done === false)
      }
      if (state.viewKey === 'done') {
        return state.list.filter(x => x.done === true)
      }
      return state.list
    }
  },
  modules: {}
})
